﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;

namespace DataCommTest.WebTest
{
    public class WebTester : ITest
    {
        #region ITest 成员

        public void Test()
        {
            int totalCount;
            var table = DemoData.GetEmployees(0, 10, out totalCount);
            Console.WriteLine(JsonHelper.ToJson(table));
        }

        #endregion
    }


    public class JsonHelper
    {
        public static bool DefaultDebug = true;
        private static readonly long DatetimeMinTimeTicks = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks;

        #region ToJson

        public static string ToJson(DataTable table)
        {
            return ToJson(table, table.Rows.Count, DefaultDebug);
        }

        public static string ToJson(DataTable table, int totalCount)
        {
            return ToJson(table, totalCount, DefaultDebug);
        }

        public static string ToJson(DataTable table, bool debug)
        {
            return ToJson(table, table.Rows.Count, debug);
        }

        public static string ToJson(DataTable table, int totalCount, bool debug)
        {
            var columns = table.Columns;
            var rows = table.Rows;

            StringBuilder builder = new StringBuilder();

            if(debug)
            {
                builder.AppendLine("{");
                builder.AppendLine("  Rows: ");
                builder.AppendLine("  [");
                builder.Append("    ");
            }
            else
            {
                builder.Append("{Rows:[");
            }

            #region Values

            RowToJson(builder, columns, rows[0], debug);
            for(int i = 1 ; i < rows.Count ; i++)
            {
                if(debug) builder.Append("    ,");
                else builder.Append(",");
                RowToJson(builder, columns, rows[i], debug);
            }

            #endregion
            if(debug)
            {
                builder.AppendLine("  ],");
                builder.AppendLine("  Total: " + totalCount);
                builder.AppendLine("}");
            }
            else
            {
                builder.Append("],Total:" + totalCount + "}");
            }
            return builder.ToString();
        }

        private static string CellToJson(object value)
        {
            if(Convert.IsDBNull(value) || value == null) return "null";
            switch(System.Type.GetTypeCode(value.GetType()))
            {
                case TypeCode.DateTime:

                    return "new Date(" + ((((DateTime)value).ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000L) + ")";

                case TypeCode.Empty:
                case TypeCode.Char:
                case TypeCode.String:
                    return "\"" + (string)value + "\"";
                case TypeCode.Byte:
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                case TypeCode.SByte:
                case TypeCode.Single:
                case TypeCode.Double:
                case TypeCode.Decimal:
                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                    return value.ToString();
                default:
                    throw new NotSupportedException(value.GetType().FullName);
                //return GlobalJson.Serialize(value);
            }
        }

        private static void RowToJson(StringBuilder builder, DataColumnCollection columns, DataRow row, bool debug)
        {
            builder.Append("{\"");
            var cells = row.ItemArray;
            builder.Append(columns[0].ColumnName);
            builder.Append("\":");
            builder.Append(CellToJson(cells[0]));

            for(int i = 0 ; i < columns.Count ; i++)
            {
                builder.Append(",\"");
                builder.Append(columns[i].ColumnName);
                builder.Append("\": ");
                builder.Append(CellToJson(cells[i]));
            }
            if(debug) builder.AppendLine("}");
            else builder.Append("}");
        }

        #endregion

        #region ToTable



        #endregion

    }

    /// <summary>
    ///DemoData 的摘要说明
    /// </summary>
    public class DemoData
    {
        static DemoData()
        {
            #region Init Departments

            Departments = new DataTable(DepartmentsName);
            Departments.Columns.Add("DepartmentID", typeof(int));
            Departments.Columns.Add("DepartmentName", typeof(string));
            Departments.Rows.Add(1, "主席");
            Departments.Rows.Add(2, "研发中心");
            Departments.Rows.Add(3, "销售部");
            Departments.Rows.Add(4, "市场部");
            Departments.Rows.Add(5, "顾问组");

            #endregion

            #region Init Employees

            Employees = new DataTable(EmployeesName);
            Employees.Columns.Add("ID", typeof(int));
            Employees.Columns.Add("DepartmentID", typeof(int));
            Employees.Columns.Add("RealName", typeof(string));
            Employees.Columns.Add("DepartmentName", typeof(string));
            Employees.Columns.Add("Sex", typeof(int));
            Employees.Columns.Add("Age", typeof(int));
            Employees.Columns.Add("IncomeDay", typeof(DateTime));
            Employees.Columns.Add("Phone", typeof(string));
            Employees.Columns.Add("Address", typeof(string));
            Random random = new Random();
            for(int i = 0 ; i < 100 ; )
            {
                i++;
                var deptID = random.Next(1, 5);
                var age = random.Next(18, 50);

                Employees.Rows.Add(i, deptID, "Employee" + i
                    , GetDepartmentName(deptID)
                    , random.Next(1, 2)
                    , age, DateTime.Now.AddYears(-age)
                    , i.ToString().PadLeft(11, '0'), "华人街" + i + "号");
            }

            #endregion
        }

        public const string DepartmentsName = "Departments";
        private readonly static DataTable Departments;
        public const string EmployeesName = "Employees";
        private readonly static DataTable Employees;

        public static int GetDepartmentCount()
        {
            return Departments.Rows.Count;
        }

        public static DataTable GetDepartments()
        {
            return Departments.Copy();
        }

        public static DataTable GetDepartment(int departmentID)
        {
            var dept2 = Departments.Clone();
            foreach(var row in Departments.Select("DepartmentID=" + departmentID))
            {
                dept2.Rows.Add(row.ItemArray);
            }
            return dept2;
        }

        public static string GetDepartmentName(int departmentID)
        {
            foreach(var row in Departments.Select("DepartmentID=" + departmentID))
            {
                return (string)row["DepartmentName"];
            }
            return null;
        }

        public static int GetEmployeeCount()
        {
            return Employees.Rows.Count;
        }

        public static DataTable GetEmployees()
        {
            return Employees.Copy();
        }

        public static DataTable GetEmployees(int pageIndex, int pageSize, out int totalCount)
        {
            totalCount = Employees.Rows.Count;
            if(pageIndex < 0) return GetEmployees();

            var newEmps = Employees.Clone();
            var start = (pageIndex * pageSize);
            var end = start + pageSize;
            for( ; start < end && start < Employees.Rows.Count ; start++)
            {
                newEmps.Rows.Add(Employees.Rows[start].ItemArray);
            }
            return newEmps;
        }
    }
}
